import { useState, useMemo } from "react"
import React from 'react'
import { useSelector, useDispatch } from 'react-redux';
import { setIsShowAddInput, addTodo, setFilter } from '../store/todoList';

function Header() {
  console.log('header组件渲染了')
  const [inputVal, setInputVal] = useState('')
  const { isShowAddInput, todoList, filter } = useSelector((state) => state.todoList)
  const dispatch = useDispatch()
  // 增
  const handleAdd = () => {
    const val = inputVal.trim()
    if (val) {
      dispatch(addTodo(val))
      setInputVal('')
      dispatch(setIsShowAddInput(false))
    }
  }
  // 计算todo done total
  const todo = useMemo(() => {
    console.log('useMemo todo 触发了')
    return todoList.filter(obj => !obj.completed).length
  }, [todoList])
  const done = useMemo(() => {
    console.log('useMemo done 触发了')
    return todoList.filter(obj => obj.completed).length
  }, [todoList])
  const total = useMemo(() => {
    console.log('useMemo total 触发了')
    return todoList.length
  }, [todoList])
  return (
    <div className="header">
      <div className="title">
        <div>事件待办</div>
        <div>
          <button className={`btn ${(filter === 'todo') && 'active'}`} onClick={() => dispatch(setFilter('todo'))}>查看未完成 {todo}</button>
          <button className={`btn ${(filter === 'done') && 'active'}`} onClick={() => dispatch(setFilter('done'))}>查看已完成 {done}</button>
          <button className={`btn ${(filter === 'all') && 'active'}`} onClick={() => dispatch(setFilter('all'))}>查看全部 {total}</button>
        </div>
      </div>
      <span className="plusIcon" onClick={() => dispatch(setIsShowAddInput(!isShowAddInput))}>+</span>
      <div className={`inputArea ${isShowAddInput && 'show'}`}>
        <input
          type="text"
          placeholder="请输入待办事项"
          className={`input`}
          value={inputVal}
          onChange={e => setInputVal(e.target.value)}
        />
        <button className="addBtn" onClick={handleAdd}>增加</button>
      </div>
    </div>
  )
}

export default React.memo(Header)